package com.whatisjee.ssf.domain.dao.impl;

import static org.apache.commons.lang.StringUtils.isNotBlank;

import java.util.List;

import com.whatisjee.ssf.domain.dao.LogDao;
import com.whatisjee.ssf.domain.entity.Log;
import com.whatisjee.ssf.misc.LogCriteria;
import com.whatisjee.ssf.misc.Page;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import javax.persistence.Query;

@Named("logDao")
@ApplicationScoped
public class LogDaoImpl extends AbstractDaoImpl implements LogDao {

	@Override
	public void save(Log log) {
		em.persist(log);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Log> select(final LogCriteria criteria, final Page page) {
                StringBuilder sb = new StringBuilder("SELECT a ");
                buildHql(sb, criteria);
                Query q = createPagedQuery(page, sb, "a");
                setParameters(q, criteria);
                return q.getResultList();
	}

	@Override
	public int selectCount(final LogCriteria criteria) {
                StringBuilder sb = new StringBuilder("SELECT COUNT(a) ");
                buildHql(sb, criteria);
                Query q = em.createQuery(sb.toString());
                setParameters(q, criteria);
                return ((Number) q.getSingleResult()).intValue();
	}

	private void buildHql(StringBuilder sb, LogCriteria criteria) {
		sb.append(" FROM Log a WHERE 1=1 ");
		if(isNotBlank(criteria.getSummary())) {
			sb.append(" AND a.summary LIKE :summary ");
		}
		if(criteria.getFrom() != null) {
			sb.append(" AND a.loggedAt >= :from ");
		}
		if(criteria.getTo() != null) {
			sb.append(" AND a.loggedAt <= :to ");
		}
		if(isNotBlank(criteria.getUsername())) {
			sb.append(" AND a.username LIKE :username ");
		}
		if(criteria.getSeverity() != null) {
			sb.append(" AND a.severity = :severity ");
		}
		if(isNotBlank(criteria.getTerminal())) {
			sb.append(" AND a.terminal = :terminal ");
		}
	}
	
	private void setParameters(Query q, LogCriteria criteria) {
		if(isNotBlank(criteria.getSummary())) {
			q.setParameter("summary", "%" + criteria.getSummary() + "%");
		}
		if(criteria.getFrom() != null) {
			q.setParameter("from", criteria.getFrom());
		}
		if(criteria.getTo() != null) {
			q.setParameter("to", criteria.getTo());
		}
		if(isNotBlank(criteria.getUsername())) {
			q.setParameter("username", "%" + criteria.getUsername() + "%");
		}
		if(criteria.getSeverity() != null) {
			q.setParameter("severity", criteria.getSeverity());
		}
		if(isNotBlank(criteria.getTerminal())) {
			q.setParameter("terminal", criteria.getTerminal());
		}
	}
}
